import 'package:sqflite/sqflite.dart';
import '../entity/game.dart';
import 'database_helper.dart';

class WishlistRepository {
  final dbHelper = DatabaseHelper.instance;

  //将游戏添加到用户的愿望单
  Future<void> addToWishlist(String userId, String gameId) async {
    final db = await dbHelper.database;
    await db.insert(
      'wishlist_items',
      {'userId': userId, 'gameId': gameId},
      conflictAlgorithm: ConflictAlgorithm.ignore, //如果记录已存在，则忽略，避免重复添加
    );
  }

  //从用户的愿望单中移除游戏
  Future<void> removeFromWishlist(String userId, String gameId) async {
    final db = await dbHelper.database;
    await db.delete(
      'wishlist_items',
      where: 'userId = ? AND gameId = ?',
      whereArgs: [userId, gameId],
    );
  }

  //检查特定游戏是否在用户的愿望单中
  Future<bool> isGameInWishlist(String userId, String gameId) async {
    final db = await dbHelper.database;
    final result = await db.query(
      'wishlist_items',
      where: 'userId = ? AND gameId = ?',
      whereArgs: [userId, gameId],
    );
    return result.isNotEmpty;
  }

  //获取一个用户愿望单中的所有游戏
  Future<List<Game>> getWishlistGamesForUser(String userId) async {
    final db = await dbHelper.database;
    //使用INNER JOIN连接wishlist_items和games表
    final List<Map<String, dynamic>> maps = await db.rawQuery('''
      SELECT g.* FROM games g
      INNER JOIN wishlist_items w ON g.id = w.gameId
      WHERE w.userId = ?
    ''', [userId]);

    return List.generate(maps.length, (i) => Game.fromMap(maps[i]));
  }
}